package com.a2.appa3.ui.fragment;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.google.gson.Gson;
import com.nanchen.compresshelper.CompressHelper;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.network.entity.req.uploadPicBean;
import com.a2.appa3.model.network.entity.req.uploadPicBena;
import com.a2.appa3.ui.activity.ExportActivity;
import com.a2.appa3.ui.activity.FeedbackActivity;
import com.a2.appa3.ui.activity.LoginActivity;
import com.a2.appa3.ui.activity.NewMessageActivity;
import com.a2.appa3.ui.activity.PasswordActivity;
import com.a2.appa3.ui.activity.ZxingActivity;
import com.a2.appa3.ui.activity.changeNikeDiolog;
import com.a2.appa3.util.ActionSheetDialog;
import com.a2.appa3.util.BaseLoadingDialog;
import com.a2.appa3.util.CleanMessageUtil;
import com.a2.appa3.util.EventBus.Eventnumber;
import com.a2.appa3.util.RoundImageView;
import com.a2.appa3.util.SYSOUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/6/21.
 * 个人中
 */

public class userFragment extends BaseFragmentSimple {
    public static final int TAKE_PHOTO = 1;
    private static final int REQUEST_GET_TAXPAYER_IMG = 106;
    RoundImageView userImg;
    TextView userName;
    TextView userCode;
    TextView daxiao;
    TextView banben;
    RelativeLayout userlayout;
    @BindView(R.id.zhanghaoguanli)
    LinearLayout zhanghaoguanli;
    @BindView(R.id.xinxiaoxitixing)
    LinearLayout xinxiaoxitixing;
    @BindView(R.id.liaotian)
    LinearLayout liaotian;
    @BindView(R.id.tongyong)
    LinearLayout tongyong;
    @BindView(R.id.wurao)
    LinearLayout wurao;
    @BindView(R.id.guanyu)
    LinearLayout guanyu;
    @BindView(R.id.bangzhu)
    LinearLayout bangzhu;
    @BindView(R.id.tuichu)
    LinearLayout tuichu;
    private ImageView pic_guidepage_3;

    public static userFragment newInstance() {

        Bundle args = new Bundle();
        userFragment fragment = new userFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int setContentView() {
        return R.layout.userfragment_layout;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pic_guidepage_3 = view.findViewById(R.id.pic_guidepage_3);
        userImg = view.findViewById(R.id.user_img);
        userName = view.findViewById(R.id.user_name);
        userCode = view.findViewById(R.id.user_code);
        userlayout = view.findViewById(R.id.userlayout);
        daxiao = view.findViewById(R.id.daxiao);
        banben = view.findViewById(R.id.banben);
        //获取当前应用缓存
        try {
            daxiao.setText(CleanMessageUtil.getTotalCacheSize(getContext()));
            PackageManager manager = getActivity().getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            String version = info.versionName;
            banben.setText("V-" + version);
            if (!TextUtils.isEmpty(Info.Token)) {
                Glide.with(getContext())
                        .load(HttpAdress.getuseAdress() + Info.user.img)
                        .error(R.mipmap.default_head)
                        .into(userImg);
                userName.setText("你好！" + Info.user.nickname);
                userCode.setText("账户号：" + Info.user.userName);
            } else {
                Glide.with(getContext())
                        .load(R.mipmap.ic_launcher)
                        .into(userImg);
                userName.setText("点击登录");
                userCode.setText("账户号：123456");
            }
            userImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(Info.Token)) {
                        Showcarmeropop();
                    } else {
                        dialog();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @OnClick({R.id.userlayout, R.id.zhanghaoguanli, R.id.xinxiaoxitixing, R.id.liaotian, R.id.tongyong, R.id.wurao, R.id.guanyu, R.id.bangzhu, R.id.tuichu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.userlayout:
                if (!TextUtils.isEmpty(Info.Token)) {
                    //二维码
                    Intent intent = new Intent(getContext(), ZxingActivity.class);
                    intent.putExtra("userid", Info.user.userId + "");
                    startActivity(intent);
                } else {
                    dialog();
                }
                break;
            case R.id.zhanghaoguanli:
                if (!TextUtils.isEmpty(Info.Token)) {
                    startActivity(new Intent(getContext(), PasswordActivity.class));
                } else {
                    dialog();
                }
                break;
            case R.id.xinxiaoxitixing:
                if (!TextUtils.isEmpty(Info.Token)) {
                    startActivity(new Intent(getContext(), NewMessageActivity.class));
                } else {
                    dialog();
                }
                break;
            case R.id.liaotian:
                if (!TextUtils.isEmpty(Info.Token)) {
                    EventBus.getDefault().post(new Eventnumber("1"));
                } else {
                    dialog();
                }
                break;
            case R.id.tongyong:
                if (!TextUtils.isEmpty(Info.Token)) {
                    startActivity(new Intent(getContext(), changeNikeDiolog.class));
                } else {
                    dialog();
                }
                break;
            case R.id.wurao:
                CleanMessageUtil.clearAllCache(getContext());
                Toast.makeText(getContext(), "清除成功", Toast.LENGTH_LONG).show();
                //获取当前应用缓存
                try {
                    daxiao.setText(CleanMessageUtil.getTotalCacheSize(getContext()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.guanyu:

                break;
            case R.id.bangzhu:
                if (!TextUtils.isEmpty(Info.Token)) {
                    startActivity(new Intent(getActivity(), FeedbackActivity.class));
                } else {
                    dialog();
                }
                break;
            case R.id.tuichu:
                if (!TextUtils.isEmpty(Info.Token)) {
                    startActivity(new Intent(getContext(), ExportActivity.class));
                } else {
                    dialog();
                }

                break;
        }
    }

    private void dialog() {
        showDialog(R.string.kong, R.string.login,
                R.string.yes,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(getContext(), LoginActivity.class));
                    }
                },
                R.string.no, null, true);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(Info.Token)) {
            Glide.with(getContext())
                    .load(HttpAdress.getuseAdress() + Info.user.img)
                    .into(userImg);
            userName.setText("你好！" + Info.user.nickname);
            userCode.setText("账户号：" + Info.user.userName);
        } else {
            Glide.with(getContext())
                    .load(R.mipmap.ic_launcher)
                    .into(userImg);
            userName.setText("点击登录");
            userCode.setText("账户号：123456");
        }
        //获取当前应用缓存
        try {
            daxiao.setText(CleanMessageUtil.getTotalCacheSize(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void Showcarmeropop() {
        //相机相册弹出框
        String sdcardState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
            new ActionSheetDialog(getContext())
                    .builder()
                    .setTitle("设置头像")
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    .addSheetItem("照相机", ActionSheetDialog.SheetItemColor.Blue,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    Opencarmore();
                                }
                            })
                    .addSheetItem("相册", ActionSheetDialog.SheetItemColor.Blue,
                            new ActionSheetDialog.OnSheetItemClickListener() {
                                @Override
                                public void onClick(int which) {
                                    Intent intent = new Intent("android.intent.action.GET_CONTENT");
                                    intent.setType("image/*");
                                    startActivityForResult(intent, REQUEST_GET_TAXPAYER_IMG);//打开系统相册
                                }

                            }).show();
        } else {
            Toast.makeText(getContext(), "sdcard已拔出，不能选择照片",
                    Toast.LENGTH_SHORT).show();
        }

    }

    private void Opencarmore() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_GET_TAXPAYER_IMG && null != data) {
            if (Build.VERSION.SDK_INT >= 19) {
                handleImageOnKitkat(data);
            }
        } else if (requestCode == TAKE_PHOTO) {
            if (Build.VERSION.SDK_INT >= 19) {
                Bundle pBundle = data.getExtras(); //从intent对象中获取数据，
                if (pBundle != null) {
                    Bitmap pBitmap = (Bitmap) pBundle.get("data");
                    if (pBitmap != null) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        pBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                        byte[] bytes = baos.toByteArray();
                        Glide.with(this)
                                .load(bytes)
                                .into(new GlideDrawableImageViewTarget(pic_guidepage_3) {
                                          @Override
                                          public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                                              super.onResourceReady(drawable, anim);
                                              scaleAndPush(drawable);
                                          }
                                      }
                                );
                    }
                }
            }
        }
    }

    private void scaleAndPush(GlideDrawable drawable) {
        pic_guidepage_3.setDrawingCacheEnabled(true);
        OutputStream os = null;
        try {
            dialog = new BaseLoadingDialog(getContext(), R.style.custom_dialog2);
            dialog.show();
            File file = new File(getActivity().getFilesDir() + "/logo.png");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            Bitmap bitmap = drawableToBitmap(drawable.getCurrent());
            SYSOUtils.sOut_("+++++++++++++++++++" + bitmap.toString());
            os = new FileOutputStream(file);
            SYSOUtils.sOut_("相机图片正常daxiao" + file.length());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
            SYSOUtils.sOut_("相机图片压缩后大小" + file.length());
            String strbm = fileToBase64(String.valueOf(file));
            post_requst_paly_1(strbm);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            pic_guidepage_3.setDrawingCacheEnabled(false);
        }
    }

    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(getContext(), uri)) {
            //如果是document类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是File类型的uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }

        displayImage(imagePath);//根据图片路径显示图片
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor = getActivity().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    Gson gson = new Gson();
    private BaseLoadingDialog dialog;

    //首先压缩图片
    public void displayImage(String path) {
        dialog = new BaseLoadingDialog(getContext(), R.style.custom_dialog2);
        dialog.show();
//        //开始上传
        File file = new File(path);
        SYSOUtils.sOut_("压缩前相ce图片正常大小" + file.length());
        File newFile = CompressHelper.getDefault(getContext()).compressToFile(file);
        SYSOUtils.sOut_("压缩后相ce图片正常大小" + newFile.length());
        String strbm = fileToBase64(String.valueOf(newFile));
        post_requst_paly_1(strbm);

    }

    //开始上传图片
    public void post_requst_paly_1(String strs) {
        Log.e("xdh", "开始上传头像");
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        uploadPicBean bean = new uploadPicBean();
        bean.picture = "data:image/png;base64," + strs;
        Log.e("xdh", strs);
        bean.token = Info.Token;
        String json = gson.toJson(bean);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        final Request request = new Request.Builder()
                .url(HttpAdress.getuseAdress() + "api/mobile/upimg")//请求的url
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                uploadPicBena bena1 = gson.fromJson(response.body().string(), uploadPicBena.class);
                if (bena1.isStatus()) {
                    userImg.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getContext(), "上传成功", Toast.LENGTH_LONG).show();
                            Glide.with(getContext())
                                    .load(HttpAdress.getuseAdress() + bena1.getUrl())
                                    .into(userImg);
                        }
                    });

                } else {
                    SYSOUtils.sOut_("上传失败，图片过大");
                }
                dialog.dismiss();

            }
        });
    }

    ////////////////////////////////////////////////////////////////////////////////
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

//        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }
}
